package reggie.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import reggie.common.R;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {
    //拿到自定义存储位置
    @Value("${reggie.path}")
    private String basePath;

    /**
     * 文件上传与下载
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    //MultipartFile是SpringMVC提供简化上传操作的工具类
    public R<String> upload(MultipartFile file) {
        //要将前端上传的文件先存到一个临时的文件  以便转存  file为临时文件

        //原始文件名
        String filename = file.getOriginalFilename();
        //切割的后缀 图片格式
        String substring = filename.substring(filename.lastIndexOf("."));
        //唯一识别码
        String uuid = UUID.randomUUID().toString();
        //合体成为新图片名
        String newFileName = uuid + substring;
        //判断配置文件是否有文件夹未创建
        File dir = new File(basePath);
        if (!dir.exists()) {
            //没就创
            dir.mkdirs();
        }
        try {

            file.transferTo(new File(basePath + newFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(newFileName);
    }
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            //输入流 读取文件
            FileInputStream fileInputStream = new FileInputStream(new File(basePath+name));

            //输出流 将读到的文件返回浏览器
            ServletOutputStream outputStream = response.getOutputStream();

            //使客户端浏览器，区分不同种类的数据
            response.setContentType("image/jpeg");

            int len=0;
            byte[] bytes = new byte[1024];
            while ((len=fileInputStream.read(bytes))!=-1){
                //从指定的字节数组开始到当前输出流关闭写入len字节
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            //关流
            outputStream.close();
            fileInputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
